<template>
  <div class="system-settings-container">
    <div class="page-header">
      <div class="header-content">
        <h1>系统设置</h1>
        <div class="title-line"></div>
      </div>
      <el-button 
        type="primary" 
        class="custom-primary-button"
        @click="saveSettings" 
        :loading="saving"
        size="medium"
      >
        <i class="el-icon-check"></i> 保存设置
      </el-button>
    </div>

    <!-- Logo设置卡片 -->
    <el-card class="settings-card logo-card">
      <div class="card-header">
        <div class="header-gradient"></div>
        <h3>系统Logo设置</h3>
      </div>
      
      <div class="logo-settings-content">
        <div class="logo-display-section">
          <div class="logo-preview-wrapper">
            <div class="logo-preview" v-if="settings.systemLogo">
              <img :src="settings.systemLogo" alt="系统Logo" class="logo-image">
              <div class="logo-overlay">
                <el-button type="text" class="remove-btn" @click="removeLogo">
                  <i class="el-icon-delete"></i> 移除
                </el-button>
              </div>
            </div>
            <div v-else class="logo-placeholder">
              <i class="el-icon-picture-outline"></i>
              <span>暂无Logo</span>
            </div>
          </div>
        </div>
        
        <div class="logo-upload-section">
          <input 
            type="file" 
            ref="fileInput"
            accept="image/jpeg,image/png,image/gif"
            @change="handleFileChange"
            style="display: none"
          >
          <el-button 
            type="primary" 
            class="upload-button"
            @click="$refs.fileInput.click()"
          >
            <i class="el-icon-upload"></i> 上传新Logo
          </el-button>
          <div class="upload-tip">
            <i class="el-icon-info"></i>
            支持JPG/PNG格式，大小不超过2MB
          </div>
        </div>
      </div>
    </el-card>

    <!-- 基本设置卡片 -->
    <el-card class="settings-card">
      <div class="card-header">
        <div class="header-gradient"></div>
        <h3>基本设置</h3>
      </div>

      <div class="form-content">
        <el-form ref="form" :model="settings" label-width="120px" class="modern-form">
          <div class="form-row">
            <el-form-item label="系统名称" class="form-item-modern">
              <el-input 
                v-model="settings.systemName" 
                placeholder="请输入系统名称"
                class="modern-input"
              ></el-input>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="系统简介" class="form-item-modern">
              <el-input 
                type="textarea" 
                v-model="settings.systemDescription" 
                :rows="4"
                placeholder="请输入系统简介"
                class="modern-textarea"
              ></el-input>
            </el-form-item>
          </div>
          
          <div class="form-row-group">
            <div class="form-row">
              <el-form-item label="客服邮箱" class="form-item-modern">
                <el-input 
                  v-model="settings.customerServiceEmail" 
                  placeholder="请输入客服邮箱"
                  class="modern-input"
                >
                  <template #prefix>
                    <i class="el-icon-message"></i>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="客服电话" class="form-item-modern">
                <el-input 
                  v-model="settings.customerServicePhone" 
                  placeholder="请输入客服电话"
                  class="modern-input"
                >
                  <template #prefix>
                    <i class="el-icon-phone"></i>
                  </template>
                </el-input>
              </el-form-item>
            </div>
          </div>
          
          <div class="form-row">
            <el-form-item label="版权信息" class="form-item-modern">
              <el-input 
                v-model="settings.copyrightInfo" 
                placeholder="请输入版权信息"
                class="modern-input"
              ></el-input>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="当前版本" class="form-item-modern">
              <el-input 
                v-model="settings.currentVersion" 
                disabled 
                placeholder="系统版本号"
                class="modern-input version-input"
              >
                <template #prefix>
                  <i class="el-icon-trophy"></i>
                </template>
              </el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from '@/store' // 导入Pinia store

const store = useStore()
const saving = ref(false)
const fileInput = ref(null)

// 系统设置数据
const settings = ref({
  settingId: null,
  systemName: '',
  systemLogo: '',
  systemDescription: '',
  customerServiceEmail: '',
  customerServicePhone: '',
  copyrightInfo: '',
  currentVersion: 'v2.5.1'
})

// 从后端获取系统设置数据
const fetchSystemSettings = async () => {
  try {
    const response = await axios.get('/api/system/settings')
    if (response.status === 200 && response.data) {
      settings.value = response.data
      // 确保Logo URL完整
      if (settings.value.systemLogo && !settings.value.systemLogo.startsWith('http')) {
        settings.value.systemLogo = `http://localhost:8081${settings.value.systemLogo}`
      }
    } else {
      ElMessage.error('获取系统设置失败')
    }
  } catch (error) {
    console.error('获取系统设置失败:', error)
    ElMessage.error('获取系统设置失败')
  }
}

// 判断是否是绝对路径
const isAbsoluteUrl = (url) => {
  return /^https?:\/\//i.test(url)
}

// 保存系统设置
const saveSettings = async () => {
  saving.value = true
  try {
    if (!settings.value.settingId) {
      ElMessage.warning('未获取到有效的设置ID，无法更新')
      return
    }
    
    const response = await axios.post('/api/system/update', settings.value)
    if (response.data > 0) {
      // 只有在保存成功后才更新store中的logo
      store.updateSystemLogo(settings.value.systemLogo)
      ElMessage.success('系统设置保存成功！')
      await fetchSystemSettings()
    } else {
      ElMessage.warning('系统设置未更新')
    }
  } catch (error) {
    console.error('保存系统设置失败:', error)
    ElMessage.error('保存系统设置失败')
  } finally {
    saving.value = false
  }
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型和大小
  const isImage = /^image\/(jpeg|png|gif)$/.test(file.type)
  const isLt2MB = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片格式文件!')
    return
  }
  if (!isLt2MB) {
    ElMessage.error('图片大小不能超过 2MB!')
    return
  }
  
  // 上传文件
  uploadFile(file)
  event.target.value = '' // 重置input
}

// 自定义上传方法
const uploadFile = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await axios.post('/api/system/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data) {
      let fileUrl = response.data
      // 确保URL完整
      if (!fileUrl.startsWith('http')) {
        fileUrl = `http://localhost:8081${fileUrl}`
      }
      // 只更新本地设置，不更新store
      settings.value.systemLogo = fileUrl
      ElMessage.success('Logo上传成功，请点击保存按钮应用更改')
    } else {
      ElMessage.error('Logo上传失败')
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')
  }
}

// 移除Logo
const removeLogo = () => {
  ElMessageBox.confirm('确定要移除当前Logo吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    settings.value.systemLogo = ''
    ElMessage.success('Logo已移除，请点击保存按钮应用更改')
  }).catch(() => {})
}

// 生命周期钩子
onMounted(() => {
  fetchSystemSettings()
})
</script>

<style scoped>
/* 整体布局 */
.system-settings-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: white;
  padding: 20px 25px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.header-content h1 {
  font-size: 24px;
  color: #1a2f54;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.title-line {
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #3b527a, #4e6694);
  border-radius: 2px;
}

/* 自定义按钮样式 */
.custom-primary-button {
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
  color: white;
  padding: 12px 24px;
  border-radius: 6px;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(26, 47, 84, 0.3);
  font-weight: 500;
}

.custom-primary-button:hover {
  background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(26, 47, 84, 0.4);
}

/* 卡片样式 */
.settings-card {
  border-radius: 10px;
  margin-bottom: 24px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  position: relative;
  padding: 16px 25px;
  margin-bottom: 20px;
}

.card-header h3 {
  color: white;
  position: relative;
  z-index: 2;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  z-index: 1;
}

/* Logo卡片特殊样式 */
.logo-card {
  margin-bottom: 24px;
}

.logo-settings-content {
  display: flex;
  gap: 30px;
  align-items: flex-start;
  padding: 0 25px 25px;
}

.logo-display-section {
  flex-shrink: 0;
}

.logo-preview-wrapper {
  position: relative;
  width: 140px;
  height: 140px;
}

.logo-preview {
  width: 100%;
  height: 100%;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.logo-preview:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.logo-preview:hover .logo-overlay {
  opacity: 1;
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #f8f9fa;
}

.logo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.remove-btn {
  color: white !important;
  font-size: 14px;
}

.remove-btn:hover {
  color: #ff6b6b !important;
}

.logo-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  color: #8c939d;
  background: #fafbfc;
  transition: all 0.3s;
}

.logo-placeholder:hover {
  border-color: #4e6694;
  color: #4e6694;
  background: #f0f5ff;
}

.logo-placeholder i {
  font-size: 32px;
  margin-bottom: 8px;
}

.logo-upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.upload-button {
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
  color: white;
  padding: 12px 20px;
  border-radius: 6px;
  transition: all 0.3s;
  margin-bottom: 15px;
  align-self: flex-start;
}

.upload-button:hover {
  background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
  transform: translateY(-2px);
}

.upload-tip {
  color: #606266;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 12px 16px;
  background: #f0f5ff;
  border-radius: 6px;
  border-left: 3px solid #4e6694;
}

/* 表单内容 */
.form-content {
  padding: 0 25px 25px;
}

.modern-form {
  max-width: 800px;
}

.form-row {
  margin-bottom: 24px;
}

.form-row-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.form-item-modern {
  margin-bottom: 0;
}

:deep(.form-item-modern .el-form-item__label) {
  color: #1a2f54;
  font-weight: 500;
  font-size: 14px;
}

.modern-input, .modern-textarea {
  border-radius: 6px;
  transition: all 0.3s;
}

:deep(.modern-input .el-input__inner),
:deep(.modern-textarea .el-textarea__inner) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

:deep(.modern-input .el-input__inner:focus),
:deep(.modern-textarea .el-textarea__inner:focus) {
  border-color: #4e6694;
  box-shadow: 0 0 0 2px rgba(78, 102, 148, 0.1);
}

:deep(.modern-input.version-input .el-input__inner) {
  background: #f8f9fa;
  color: #606266;
}

:deep(.modern-input .el-input__prefix) {
  color: #4e6694;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .form-row-group {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .logo-settings-content {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .logo-upload-section {
    align-items: center;
  }
  
  .upload-button {
    align-self: center;
  }
}

@media (max-width: 768px) {
  .system-settings-container {
    padding: 15px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .logo-preview-wrapper {
    width: 120px;
    height: 120px;
  }
  
  .form-content,
  .logo-settings-content {
    padding: 0 20px 20px;
  }
}

/* 动画效果 */
.settings-card {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.logo-card {
  animation-delay: 0.1s;
}

.settings-card:last-child {
  animation-delay: 0.2s;
}
</style>